package com.ruoyi.datastatistics.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.mapper.TerminalsDbMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.datastatistics.domain.MeterHistoryData;
import com.ruoyi.datastatistics.domain.Realtimegatherdata;
import com.ruoyi.datastatistics.domain.RealtimegatherdataXb;
import com.ruoyi.datastatistics.domain.TerminalHistoryData;
import com.ruoyi.datastatistics.domain.recvdata.RecvDataDb;
import com.ruoyi.datastatistics.mapper.*;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.datastatistics.service.RecvDataService;
import com.ruoyi.datastatistics.domain.recvdata.RecvData;
import com.ruoyi.datastatistics.domain.recvdata.RecvDataXb;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author zhangjie
 */
@Service
public class RecvDataServiceImpl implements RecvDataService {
    private final RecvDataMapper recvDataMapper;

    private final RealtimegatherdataXbMapper realtimegatherdataXbMapper;

    private final TerminalsXbMapper terminalsXbMapper;

    private final MeterHistoryDataMapper meterHistoryDataMapper;

    private final RealtimegatherdataMapper realtimegatherdataMapper;

    private final TerminalsDbMapper terminalsDbMapper;

    private final TerminalHistoryDataMapper terminalHistoryDataMapper;

    public RecvDataServiceImpl(RecvDataMapper recvDataMapper, RealtimegatherdataXbMapper realtimegatherdataXbMapper, TerminalsXbMapper terminalsXbMapper, MeterHistoryDataMapper meterHistoryDataMapper, RealtimegatherdataMapper realtimegatherdataMapper, TerminalsDbMapper terminalsDbMapper, TerminalHistoryDataMapper terminalHistoryDataMapper) {
        this.recvDataMapper = recvDataMapper;
        this.realtimegatherdataXbMapper = realtimegatherdataXbMapper;
        this.terminalsXbMapper = terminalsXbMapper;
        this.meterHistoryDataMapper = meterHistoryDataMapper;
        this.realtimegatherdataMapper = realtimegatherdataMapper;
        this.terminalsDbMapper = terminalsDbMapper;
        this.terminalHistoryDataMapper = terminalHistoryDataMapper;
    }

    /**
     * 把接收到的数据存入中间库
     *
     * @param recvData 接收到的数据
     * @return 是否成功
     */
    @Override
    public boolean saveRecvData(RecvData recvData) {
        return recvDataMapper.insertRecvData(recvData) > 0;
    }

    /**
     * 把接收到的数据存入中间库
     *
     * @param recvData 接收到的数据
     * @return 是否成功
     */
    @Override
    public boolean saveRecvDataXb(RecvDataXb recvData) {
        return recvDataMapper.batchInsertOrUpdateRecvDataXb(recvData) > 0;
    }

    @Override
    public boolean saveRealtimeDataXb(RecvDataXb recvData) {
        RecvDataXb.XbData realtimeData = recvData.getRealtimeData();
        RealtimegatherdataXb realtimegatherdataXb = realtimegatherdataXbMapper.selectRealtimeDataByTerminalIdAndTenantId(recvData.getDeviceNumber(), recvData.getClientId());
        if (realtimegatherdataXb == null) {
            realtimegatherdataXb = new RealtimegatherdataXb();
            realtimegatherdataXb.setTerminalId(recvData.getDeviceNumber());
            realtimegatherdataXb.setTenantId(recvData.getClientId());
            TerminalsXb terminalsXb = terminalsXbMapper.selectTerminalsXbByTerminalID(recvData.getDeviceNumber());
            realtimegatherdataXb.setLocationNb(terminalsXb.getLocationNb());
            realtimegatherdataXb.setCreateTime(new Date());
        }
        realtimegatherdataXb.setTotalFlow(realtimeData.getTotalFlow());
        realtimegatherdataXb.setTerminalCsq(realtimeData.getTerminalCsq());
        realtimegatherdataXb.setTerminalVol(realtimeData.getTerminalVol());
        realtimegatherdataXb.setValveState(Convert.toBigDecimal(realtimeData.getValveState()));
        realtimegatherdataXb.setReadDate(realtimeData.getReadDate());
        boolean success;
        if (realtimegatherdataXb.getId() == null) {
            success = realtimegatherdataXbMapper.insert(realtimegatherdataXb) > 0;
        } else {
            success = realtimegatherdataXbMapper.updateById(realtimegatherdataXb) > 0;
        }
        return success;
    }

    /**
     * 保存户表历史数据
     */
    @Override
    public void saveHistoryDataXb() {
        List<RecvDataXb.XbData> xbDataList = recvDataMapper.selectRecvXbData();
        List<Long> successIds = new ArrayList<>();
        List<Long> failIds = new ArrayList<>();
        for (RecvDataXb.XbData xbData : xbDataList) {
            if (StringUtils.isBlank(xbData.getLocationNb())) {
                failIds.add(xbData.getId());
                continue;
            }
            MeterHistoryData meterHistoryData = BeanUtil.copyProperties(xbData, MeterHistoryData.class, "id");
            meterHistoryData.setReadDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, xbData.getReadDate()));
            meterHistoryData.setCreateDate(new Date());
            int rows = meterHistoryDataMapper.insert(meterHistoryData);
            if (rows > 0) {
                successIds.add(xbData.getId());
            } else {
                failIds.add(xbData.getId());
            }
        }
        String tableName = "t_recv_data_xb";
        recvDataMapper.updateSyncStatusByIds(tableName, "2", successIds);
        recvDataMapper.updateSyncStatusByIds(tableName, "3", failIds);
    }

    /**
     * 把接收到的大表数据存入中间库
     *
     * @param recvData 接收到的数据
     * @return 是否成功
     */
    @Override
    public boolean saveRecvDataDb(RecvDataDb recvData) {
        boolean success = false;
        // 保存实时数据
        RecvDataDb.DbData realtimeData = recvData.getRealtimeData();
        if (realtimeData != null) {
            success = saveRealtimeDataDb(recvData);
        }
        // 保存历史数据
        if (CollectionUtils.isNotEmpty(recvData.getHistoryData())) {
            success = success && (recvDataMapper.batchInsertOrUpdateRecvDataDb(recvData) > 0);
        }
        return success;
    }

    private boolean saveRealtimeDataDb(RecvDataDb recvData) {
        RecvDataDb.DbData realtimeData = recvData.getRealtimeData();
        Realtimegatherdata realtimegatherdata = realtimegatherdataMapper.selectRealtimegatherdataByTerminalIdAndTenantId(recvData.getDeviceNumber(), recvData.getClientId());
        if (realtimegatherdata == null) {
            realtimegatherdata = new Realtimegatherdata();
            realtimegatherdata.setTerminalId(recvData.getDeviceNumber());
            realtimegatherdata.setTenantId(recvData.getClientId());
            TerminalsDb terminalsDb = terminalsDbMapper.selectTerminalsDbByTerminalId(recvData.getDeviceNumber());
            realtimegatherdata.setLocationNb(terminalsDb.getLocationNb());
            realtimegatherdata.setCreateTime(new Date());
        }
        realtimegatherdata.setTotalFlow(realtimeData.getTotalFlow());
        realtimegatherdata.setReadNumber(realtimeData.getReadNumber());
        realtimegatherdata.setReverseNumber(realtimeData.getReverseNumber());
        realtimegatherdata.setInstantNumber(realtimeData.getInstantNumber());
        realtimegatherdata.setInstantVelocity(realtimeData.getInstantVelocity());
        realtimegatherdata.setPressure(realtimeData.getPressure());
        realtimegatherdata.setTerminalCsqDescribe(realtimeData.getTerminalCsqDescribe());
        realtimegatherdata.setTerminalCsq(Convert.toLong(realtimeData.getTerminalCsq()));
        realtimegatherdata.setTerminalVol(realtimeData.getTerminalVol());
        realtimegatherdata.setValveState(realtimeData.getValveState());
        realtimegatherdata.setReadDate(realtimeData.getReadDate());
        boolean success;
        if (realtimegatherdata.getId() == null) {
            success = realtimegatherdataMapper.insert(realtimegatherdata) > 0;
        } else {
            success = realtimegatherdataMapper.updateById(realtimegatherdata) > 0;
        }
        return success;
    }

    /**
     * 保存大表历史数据
     */
    @Override
    public void saveHistoryDataDb() {
        List<RecvDataDb.DbData> dbDataList = recvDataMapper.selectRecvDbData();
        List<Long> successIds = new ArrayList<>();
        List<Long> failIds = new ArrayList<>();
        for (RecvDataDb.DbData dbData : dbDataList) {
            if (StringUtils.isBlank(dbData.getLocationNb())) {
                failIds.add(dbData.getId());
                continue;
            }
            TerminalHistoryData terminalHistoryData = BeanUtil.copyProperties(dbData, TerminalHistoryData.class, "id");
            terminalHistoryData.setCreateTime(new Date());
            int rows = terminalHistoryDataMapper.insert(terminalHistoryData);
            if (rows > 0) {
                successIds.add(dbData.getId());
            } else {
                failIds.add(dbData.getId());
            }
        }
        String tableName = "t_recv_data_db";
        recvDataMapper.updateSyncStatusByIds(tableName, "2", successIds);
        recvDataMapper.updateSyncStatusByIds(tableName, "3", failIds);
    }

    @Override
    public void deleteRecvDataRegularly() {
        recvDataMapper.deleteRecvData();
    }
}
